import { Message } from 'element-ui'
import axios from 'axios'
import store from '@/store'
// import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use((config) => {
  // 请求头注入token
  if (store.getters.token) {
    config.headers.token = store.getters.token
  }
  return config
}, (error) => {
  // 失败执行promise
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use((response) => {
  const { data, code, msg } = response.data // 默认json格式
  if (msg === '删除成功') Message({ type: 'success', message: msg })
  if (code === 200) {
    return data
  } else if (code === 403) {
    Message({ type: 'error', message: '错误！请重试' })
    // store.dispatch('user/logout')
    // router.push('/login')
    nprogress.done()
    return Promise.reject(new Error(msg))
  } else if (code === 401) {
    Message({ type: 'warning', message: msg })
    setTimeout(() => {
      store.dispatch('user/logout')
      location.reload()
    }, 1000)
  } else if (code === 404) {
    Message({ type: 'error', message: msg })
  } else {
    // 其他code 提示
    Message({ type: 'error', message: msg })
    return Promise.reject(new Error(msg))
  }
}, async(error) => {
  // error.message
  Message({ type: 'error', message: '网络请求错误,请重试！' })
  return Promise.reject(error)
})

export default service
